import React, { useState, useEffect, useRef } from 'react';
import { Tabs, Card, Button, message, Icon } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import moment from 'moment';
import _ from 'lodash';
import ProjectsPath from '@/components/ProjectsPath';
import AuthorizedButton from '@/components/AuthorizedButton';
import router from 'umi/router';

import Formal from './components/Formal'; // 正式版
import Adjustment from './components/Adjustment'; // 调整版
import EditTable from './EditTable'; // 调整版编辑
import Actual from './components/Actual'; // 实际版

import {
  CONSTANT_TAB_KEY1, // 投资正式版
  CONSTANT_TAB_KEY2, // 调整版
  CONSTANT_TAB_KEY3, // 实际版
} from './utils/constant';
import * as apis from '@/services/ReturnMoneyValueMgr';

const { TabPane } = Tabs;

const InvestmentView = props => {
  const childRef = useRef();
  const { versionActive } = props;
  const [state, setState] = useState({
    activeKey: CONSTANT_TAB_KEY1, // 初始版
    version: null,
    // version: { id: 'ac66182d6bf14a89ba19a727550b7aca',versionState:'not_prepared' },
  });

  const [isEdit, setIsEdit] = useState(false); // 展示编辑页面
  // const [isEdit, setIsEdit] = useState(true); // 展示编辑页面
  const [createLoading, setCreateLoading] = useState(false);
  const [approveBtnShow, setApproveBtnShow] = useState(false);
  const [approveLoading, setApproveLoading] = useState(false);
  const [reloadLoading, setReloadLoading] = useState(false);

  useEffect(() => {
    // 切换项目关闭编辑状态
    if (isEdit) setIsEdit(false);
  }, [props.match.params.project]);

  // 创建新版本
  const createVersion = async () => {
    const projectId = props.match.params.project;
    setCreateLoading(true);
    apis
      .createUsingPOST({ params: { projectId } })
      .then(res => {
        if (res && res.code === 1) {
          setState({
            ...state,
            version: res.data,
          });
          setIsEdit(true);
        }
      })
      .then(() => setCreateLoading(false));
  };

  // 投资正式版刷新
  const handlerReload = async () => {
    setReloadLoading(true);
    childRef.current.changeUpData(() => setReloadLoading(false));
  };
  // 调整版新建版本button
  const createButton = () => {
    if (CONSTANT_TAB_KEY1 === state.activeKey) {
      return (
        <AuthorizedButton authority="business_payBackModulus_refresh">
          <Button onClick={handlerReload} loading={reloadLoading}>
            刷新
            <Icon type="reload" />
          </Button>
        </AuthorizedButton>
      );
    }
    if (CONSTANT_TAB_KEY2 === state.activeKey) {
      return (
        <AuthorizedButton authority="business_payBackModulus_createAdjustment">
          <Button onClick={createVersion} loading={createLoading} type="primary">
            创建版本
          </Button>
        </AuthorizedButton>
      );
    }
    return null;
  };

  // 发起审批
  const handApprove = async () => {
    if (!versionActive && !versionActive.id) {
      message.warnding('暂无调整版版本');
      return;
    }
    setApproveLoading(true);
    const res = await apis.approvedCheckUsingGET_1({ params: { versionId: versionActive.id } });
    setApproveLoading(false);
    if (!res || res.code !== 1) {
      return;
    }
    window.open(
      `${window.location.origin}#/common/PayBackModulusApprove?vId=${versionActive.id}&pId=${props.match.params.project}&action=modify`,
    );
    // router.push({
    //   pathname: '/common/PayBackModulusApprove',
    //   query: { vId: versionActive.id, pId: props.match.params.project, action: 'modify' },
    // });
  };

  return (
    <PageHeaderWrapper
      className="page-header"
      breadcrumb={null}
      title={<ProjectsPath menu="SupplyPlan" {...props} />}
      extra={
        approveBtnShow &&
        !isEdit && (
          <AuthorizedButton authority="business_payBackModulus_startApprove">
            <Button loading={approveLoading} type="primary" onClick={handApprove}>
              发起审批
            </Button>
          </AuthorizedButton>
        )
      }
    >
      <Card className="page-header-card" bordered={false}>
        {isEdit ? (
          <EditTable
            version={state.version}
            close={() => {
              setIsEdit(false);
              setState({ ...state, activeKey: CONSTANT_TAB_KEY2 });
            }}
            {...props}
          />
        ) : (
          <>
            <Tabs
              tabBarExtraContent={createButton(state.activeKey)}
              onChange={activeKey => {
                setState({ ...state, activeKey });
                setApproveBtnShow(false);
              }}
              activeKey={state.activeKey}
              animated={false}
              size="large"
            >
              <TabPane tab="投资正式版" key={CONSTANT_TAB_KEY1} />
              <TabPane tab="调整版" key={CONSTANT_TAB_KEY2} />
              <TabPane tab="实际版" key={CONSTANT_TAB_KEY3} />
            </Tabs>

            {// 正式版
            CONSTANT_TAB_KEY1 === state.activeKey && <Formal {...props} onRef={childRef} />}
            {// 调整版
            CONSTANT_TAB_KEY2 === state.activeKey && (
              <Adjustment
                {...props}
                activeKey={state.activeKey}
                showApproveBtn={() => setApproveBtnShow(true)}
                edit={version => {
                  setState({ ...state, version });
                  setIsEdit(true);
                }}
              />
            )}
            {// 实际版
            CONSTANT_TAB_KEY3 === state.activeKey && <Actual {...props} />}
          </>
        )}
      </Card>
    </PageHeaderWrapper>
  );
};

export default connect(state => ({
  orgStructure: state.orgStructure,
  versionList: state.PayBackModulus.versionList,
  versionActive: state.PayBackModulus.versionActive,
}))(InvestmentView);
